package cn.ecpay.unionpay.settle.notify;

import cn.ecpay.unionpay.settle.Common.DateUtil;
import cn.ecpay.unionpay.settle.dao.QuotaIncreaseDao;
import cn.ecpay.unionpay.settle.entity.db.TPvQuotaIncrease;
import cn.ecpay.unionpay.settle.util.CommonBase;
import cn.ecpay.unionpay.settle.util.FsasService;
import cn.ecpay.unionpay.settle.util.LogUtil;
import org.rex.db.exception.DBException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 额度调增通知
 * Created by zhaoyanzeng on 2018/11/26.
 */
@Component
public class QuotaIncreaseNotify {

    @Resource
    private QuotaIncreaseDao quotaIncreaseDao;

    public void quotaIncrease(Map<String,String> reqParam)
            throws ServletException, IOException {
        LogUtil.writeLog("额度调增通知开始");
        TPvQuotaIncrease quotaIncrease = convertReturnMoney(reqParam);
        LogUtil.printRequestLog(reqParam);
        if (!FsasService.validate(reqParam, CommonBase.encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");
            quotaIncrease.setNotifyValidate("0");
            //验签失败，需解决验签问题
        } else {
            LogUtil.writeLog("验证签名结果[成功].");
            quotaIncrease.setNotifyValidate("1");
            String respCode = reqParam.get("respCode"); //获取后台通知的数据，其他字段也可用类似方式获取
            LogUtil.writeLog("respCode=" + respCode);
        }
        try {
            quotaIncreaseDao.updateNotify(quotaIncrease);
        } catch (DBException e) {
            LogUtil.writeLog("更新额度调增通知失败");
            e.printStackTrace();
        }
        LogUtil.writeLog("额度调增通知结束");
    }

    private TPvQuotaIncrease convertReturnMoney(Map<String, String> reqParam) {
        TPvQuotaIncrease quotaIncrease = new TPvQuotaIncrease();
        quotaIncrease.setTxnNo(reqParam.get("txnNo"));
        quotaIncrease.setNotifyRespCode(reqParam.get("respCode"));
        quotaIncrease.setNotifyRespMsg(reqParam.get("respMsg"));
        quotaIncrease.setAcsAcctBal(reqParam.get("acsAcctBal"));
        quotaIncrease.setAvlbQuotaAmt(reqParam.get("avlbQuotaAmt"));
        quotaIncrease.setProAcctBal(reqParam.get("proAcctBal"));
        quotaIncrease.setAcctDate(reqParam.get("acctDate"));
        quotaIncrease.setNotifyTime(DateUtil.getDateTo19(new Date()));
        quotaIncrease.setIsNotify("1");
        return quotaIncrease;
    }
}
